<?php

namespace App\Http\Controllers\Api;


use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;


class WechatController extends Controller
{

    protected $config;
    protected $app;

    public function __construct()
    {

        $this->config = [
            'app_id' => 'wx2ac5615f35ce3ee1',
            'secret' => 'dcf55dfda6e4e0f26cc3fc91fed5e402',


            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

//            'log' => [
//                'level' => 'debug',
//                'file' => __DIR__ . '/wechat.log',
//            ],
        ];
        $this->app = Factory::miniProgram($this->config);


    }

    public function getAccessToken(){
        $accessToken = $this->app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串

        return $token['access_token'];
    }

    //根据code获取 sessionkey和openid
    public function getOpenidFromCode(Request $request){

        $code = $request->code;
        $result = $this->app->auth->session($code);


        if(isset($result['openid'])&&$result['openid']){

            return  $this->success($result);
        }else{
            return $this->failed('获取失败');
        }
    }


    //消息解密
    public function encryptor($session,$iv,$encryptedData){
        $decryptedData = $this->app->encryptor->decryptData($session, $iv, $encryptedData);
        return $decryptedData;
    }

    //发送订阅消息
    public function send_msg($user_id,$tmp_id='J53A-jfzTTRliQ0qwpCAZF6v_-OGH8pqlD_o72LYpS4'){

        $user = DB::table('users')->find($user_id);

        if(!$user->openid){
            return false;
        }

        if($user->status==1){
            $str = '审核通过';
        }
        if($user->status==2){
            $str = '审核未通过';
        }
        $company = DB::table('company')->find($user->company_id);
        $data = [
            'template_id' => $tmp_id, // 所需下发的订阅模板id
            'touser' => $user->openid,     // 接收者（用户）的 openid
            'page' => 'pages/index/index',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。

            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'phrase1' => [
                    'value' => $str,
                ],
                'thing2' => [
                    'value' => $company->name.'员工审核',
                ],
                'date3' => [
                    'value' =>  date("Y-m-d H:i:s",time()),
                ],
                'thing5' => [
                    'value' => "如有疑问请联系相关人员",
                ],
            ],
            //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
            'miniprogram_state' => 'trial'
        ];

       return $this->app->subscribe_message->send($data);
    }
}
